package com.dshore.messagecenter.service.technology.impl;


import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.stereotype.Service;

import com.dshore.messagecenter.service.technology.EmailService;
@Service
public class EmailServiceImpl implements EmailService {

	@Override
	public void sendEmail(String text) {
		
		try{
			String host = "smtp.qq.com";//这是QQ邮箱的smtp服务器地址
			String port = "25"; //端口号
			
			//roperties是一个属性对象，用来创建Session对象
			Properties props = new Properties();
			props.setProperty("mail.smtp.host", host);
			props.setProperty("mail.smtp.port", port);
			props.setProperty("mail.smtp.auth", "true");
			props.setProperty("mail.smtp.ssl.enable", "false");//"true"
			props.setProperty("mail.smtp.connectiontimeout", "5000");
			final String user = "727612821@qq.com";//用户名
			final String pwd = "hyysfozadhzgbfhj";//授权码
			
			//Session类定义了一个基本的邮件对话。
			Session session = Session.getInstance(props, new Authenticator() {
				@Override
            	protected PasswordAuthentication getPasswordAuthentication() {
                //登录用户名密码
					return new PasswordAuthentication(user,pwd);
				}
			});
        
			session.setDebug(true);
			
			/*
	        *Transport类用来发送邮件。
	        *传入参数smtp，transport将自动按照smtp协议发送邮件。
	        */
			Transport transport = session.getTransport("smtp");//"smtps"
			transport.connect(host,user,pwd);
			
			//Message对象用来储存实际发送的电子邮件信息
			MimeMessage message = new MimeMessage(session);
			message.setSubject("邮件标题");
        
			message.setFrom(new InternetAddress(user,"发件人昵称"));
        	message.addRecipients(Message.RecipientType.TO,new InternetAddress[]{
        			//消息接收者(收件地址，昵称)
        			//不过这个昵称貌似没有看到效果
        			new InternetAddress("18751879373@163.com","收件人昵称"),
        	});
        	message.saveChanges();
        	//设置邮件内容及编码格式
        	message.setContent(text, "text/plain;charset=UTF-8");
        	//发送
        	Transport.send(message);
        	transport.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
}